﻿#include "threadpool.h"

ThreadPool::ThreadPool()
{
    m_stop = false;
}

ThreadPool::~ThreadPool()
{
    releaseThreadPool();
}

void ThreadPool::initThreadPool(int threadNum)
{
    //定义线程执行函数
    auto func = ([this]()
    {
        while(1)
        {
            Task task;

            {
                std::unique_lock<std::mutex> lock(this->m_mutex);
                this->m_cond.wait(lock, [this] { return this->m_stop || !this->m_tasks.empty(); });
                if (this->m_stop)
                {
                    printf("thread stop id=%d\n", std::this_thread::get_id());
                    return;
                }

                task = std::move(this->m_tasks.front());
                this->m_tasks.pop();
            }

            //执行任务
            task();
        }
    });

    //加入线程列表
    for (int i=0; i<threadNum; ++i)
    {
        std::thread t(func);
        m_workers.push_back(std::move(t));
    }   
}

void ThreadPool::releaseThreadPool()
{
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_stop = true;
    }
    m_cond.notify_all();

    for(std::thread &worker: m_workers)
    {
        if(worker.joinable())
            worker.join();
    }

    while(!m_tasks.empty())
        m_tasks.pop();
}

void ThreadPool::commitTask(Task task)
{
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_tasks.emplace(task);
    }

    m_cond.notify_one();
}

